from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

class SearchForm(forms.Form):
    query = forms.CharField(label=(u'Search Query'), required=False)

    def getQuery(self):
        data = self.cleaned_data
        return data['query']

def search(query):
    if query == '':
        model_results = User.objects.all()
    else:
        last_results = User.objects.filter(last_name__icontains=query)
        first_results = User.objects.filter(first_name__icontains=query)
        model_results = last_results | first_results
    results = [ {"first_name":x.first_name, "last_name":x.last_name, "username":x.username, "user_pk":x.pk } for x in model_results ]
    return results

def formatResults(results):
    formatted_results = []
    for result in results:
        formatted = {}
        formatted["first"] = result["first_name"]
        formatted["last"] = result["last_name"]
        formatted["username"] = result["username"]
        formatted["pk"] = result["user_pk"]
        formatted_results.append(formatted)
    return formatted_results

@login_required(login_url='accounts/login/')
def renderSearch(request):
    if request.user.profile.gym_staff or request.user.is_staff:
        query = ''
        if request.method == 'POST':
            form = SearchForm(request.POST)
            if form.is_valid():
                query = form.getQuery()
        else:
            form = SearchForm()
        results = search(query)
        formatted_results = formatResults(results)
        return render_to_response("usersearch/search.html", {'form':form, 'results':formatted_results,
                                'csrf_token':csrf(request)['csrf_token']}, context_instance=RequestContext(request))
    else:
        return render_to_response("unauth.html", {}, context_instance=RequestContext(request))
